package com.net

import android.util.Log
import okhttp3.Call
import okhttp3.EventListener
import okhttp3.Protocol
import java.io.IOException
import java.net.InetAddress
import java.net.InetSocketAddress
import java.net.Proxy

/**
 * @describe:
 * @Author: lixiaopeng
 * @Date: 2021/7/23
 */
class OKHttpEventListener : EventListener() {

    private val event = OkHttpEvent()

    companion object {
        private var tag: String = "OKHttpEventListener"
        fun get(tag: String): Factory {
            this.tag = tag
            return FACTORY
        }

        private val FACTORY = object : Factory {
            override fun create(call: Call): EventListener {
                return OKHttpEventListener()
            }
        }
    }

    override fun responseBodyEnd(call: Call, byteCount: Long) {
        super.responseBodyEnd(call, byteCount)
        event.responseBodySize = byteCount
        event.url = call.request().url.host + call.request().url.encodedPath
    }

    override fun callEnd(call: Call) {
        super.callEnd(call)
        event.requestSuccess = true
        Log.d(tag, event.toString())
    }

    override fun callFailed(call: Call, ioe: IOException) {
        super.callFailed(call, ioe)
        event.requestSuccess = false
        event.errorStack = Log.getStackTraceString(ioe)
        Log.d(tag, event.toString())
    }

    override fun connectStart(call: Call, inetSocketAddress: InetSocketAddress, proxy: Proxy) {
        super.connectStart(call, inetSocketAddress, proxy)
        event.startTime = System.currentTimeMillis()
    }

    override fun connectEnd(call: Call, inetSocketAddress: InetSocketAddress, proxy: Proxy, protocol: Protocol?) {
        super.connectEnd(call, inetSocketAddress, proxy, protocol)
        event.endTime = System.currentTimeMillis()
    }


    class OkHttpEvent {

        var url = ""

        //是否请求成功
        var requestSuccess = false

        //耗时
        var startTime = 0L
        var endTime = 0L

        //响应体 大小
        var responseBodySize = 0L

        //错误原因
        var errorStack: String? = null

        override fun toString(): String {
            return "OkHttpEvent(url=$url, requestSuccess=$requestSuccess, 请求耗时=${endTime - startTime}, responseBodySize=$responseBodySize, errorStack=$errorStack)"
        }
    }
}